<?php
class Admin_backup_file_Controller extends Template_Controller {
	
	public $search;
	public $template = 'admin/index';
	
    public function __construct()
    {
        parent::__construct();
        
       
    }
    
	public function __call($method, $arguments)
	{
		// Disable auto-rendering
		$this->auto_render = FALSE;
	}
	
	public function index()
    {	
        $this->template->content = new View('admin_backup_file/frm');
    }
    public function backup()
	{
		$zip = new ZipArchive();
		$zip->open('Backup_'.date('m-d-Y').'.zip', ZipArchive::CREATE);
		
		$dirName = 'uploads';
		
		if (!is_dir($dirName)) {
			throw new Exception('Directory ' . $dirName . ' does not exist');
		}
		
		$dirName = realpath($dirName);
		if (substr($dirName, -1) != '/') {
			$dirName.= '/';
		}
		
		/*
		 * NOTE BY danbrown AT php DOT net: A good method of making
		 * portable code in this case would be usage of the PHP constant
		 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
		 */
		
		$dirStack = array($dirName);
		//Find the index where the last dir starts
		$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;
		
		while (!empty($dirStack)) {
			$currentDir = array_pop($dirStack);
			$filesToAdd = array();
		
			$dir = dir($currentDir);
			while (false !== ($node = $dir->read())) {
				if (($node == '..') || ($node == '.')) {
					continue;
				}
				if (is_dir($currentDir . $node)) {
					array_push($dirStack, $currentDir . $node . '/');
				}
				if (is_file($currentDir . $node)) {
					$filesToAdd[] = $node;
				}
			}
		
			$localDir = substr($currentDir, $cutFrom);
			$zip->addEmptyDir($localDir);
		   
			foreach ($filesToAdd as $file) {
				$zip->addFile($currentDir . $file, $localDir . $file);
			}
		}
		
		$zip->close();
		$file = 'Backup_'.date('m-d-Y').'.zip';
		if (file_exists($file)) {
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expires: 0');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			ob_clean();
			flush();
			readfile($file);
			exit;
		}	
	}
	
	
  public function restore()	
  {
		
		$_FILES = Validation::factory($_FILES)
			->add_rules('txt_restore_file', 'upload::valid', 'upload::type[xls,zip,gz]', 'upload::size[10M]');
			
		if($_FILES['txt_restore_file']['error']==0)
		{
			Kohana::config_set('upload.directory', DOCROOT);
			$filename = upload::save('txt_restore_file');	
						
		} else {
			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));
		}
	}

}
?>